//
//  SYUploadAvaterManager.m
//  siyanone
//
//  Created by LK-IOS on 2018/3/26.
//  Copyright © 2018年 LK-News. All rights reserved.
//

#import "SYUploadAvaterManager.h"
#import "HXPhotoPicker.h"
#import <AFNetworking.h>

@interface SYUploadAvaterManager()

@property (nonatomic, copy)UploadFinish uploadFinish;


@end

@implementation SYUploadAvaterManager


+ (void)startUploadFinshWithImage:(UIImage *)image finish:(UploadFinish)uploadFinish
{
    SYUploadAvaterManager *manager = [[SYUploadAvaterManager alloc] init];
    [manager startUploadFinshWithImage:image finish:uploadFinish];
}


-(void)startUploadFinshWithImage:(UIImage *)image finish:(UploadFinish)uploadFinish;
{
    self.uploadFinish = uploadFinish;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:[SYUserDataManger sharedInstance].getUserToken forHTTPHeaderField:@"Authorization"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json", nil];
    //POST /publisher/headPortrait
    NSString *url = [NSString stringWithFormat:@"%@%@",baseUrlHttp,@"/publisher/headPortrait"];
    
    
    //formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        DDLog(@"----图片的大小%fK--------",data.length/1024.0);
        
        
        
        
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        //        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        //        // 设置时间格式
        //        formatter.dateFormat = @"yyyyMMddHHmmss";
        //        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@_%@.jpg",[SYUserDataManger sharedInstance]. getUerPhone,@"userAvater"];
        
        //上传
        /*
         此方法参数
         1. 要上传的[二进制数据]
         2. 对应网站上[upload.php中]处理文件的[字段"file"]
         3. 要保存在服务器上的[文件名]
         4. 上传文件的[mimeType]
         */
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //上传进度
        // @property int64_t totalUnitCount;     需要下载文件的总大小
        // @property int64_t completedUnitCount; 当前已经下载的大小
        //
        // 给Progress添加监听 KVO
        NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        // 回到主队列刷新UI,用户自定义的进度条
        dispatch_async(dispatch_get_main_queue(), ^{
            //            self.progressView.progress = 1.0 *
            //            uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 200) {
            uploadFinish(responseObject[@"result"]);
        }else
        {
            uploadFinish(@"error");
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DDLog(@"error = %@" , error)
        uploadFinish(@"error");
    }];
}




@end
